package com.controller;

import com.dto.BookDTO;
import com.dto.TypeDTO;
import com.service.BookServiceImpl;
import com.service.LoginServiceImpl;
import com.util.LykFileUtil;
import com.util.Result;
import com.util.ResultUtil;
import io.swagger.annotations.ApiImplicitParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linyukun
 * @date 2022/7/7 19:10
 */
@RequestMapping("book")
@RestController
public class BookController {

    @Autowired
    private BookServiceImpl bookServiceImpl;

    @Autowired
    private LoginServiceImpl loginServiceImpl;

    @Value("${image.upload.path}")
    private String imageUploadPath;

    //审核中的数据
    private volatile Map<String,String> bookControllerMap = new HashMap<>();
    private static final String bookControllerMapSeparator = "*****";

    /**
     * 获取图书列表
     * @author linyukun
     * @date 2022-07-09 10:36
     */
    @RequestMapping(value="/getBookList",method = RequestMethod.POST)
    public Result getBookList(@RequestBody BookDTO dto){
        try{
            loginServiceImpl.isLogin();
            return ResultUtil.returnDataSuccess(bookServiceImpl.getBookList(dto));
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.returnFailMsg(e.getMessage());
        }
    }

    /**
     * 添加书籍
     * @author linyukun
     * @date 2022-07-09 10:36
     */
    @RequestMapping(value="/addBook",method = RequestMethod.POST)
    public Result addBook(@RequestBody BookDTO dto){
        try{
            String userName = loginServiceImpl.isLogin();
            dto.setCreateUser(userName);
            return ResultUtil.returnDataSuccess(bookServiceImpl.addBook(dto));
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.returnFailMsg(e.getMessage());
        }
    }

    /**
     * 编辑书籍
     * @author linyukun
     * @date 2022-07-09 10:36
     */
    @RequestMapping(value="/editBook",method = RequestMethod.POST)
    public Result editBook(@RequestBody BookDTO dto){
        String judgeKey = "editBook" + bookControllerMapSeparator + dto.getId();
        try{
            loginServiceImpl.judgeIsOnTimeRequest(bookControllerMap, judgeKey);
            String userName = loginServiceImpl.isLogin();
            dto.setUpdateUser(userName);
            return ResultUtil.returnDataSuccess(bookServiceImpl.editBook(dto));
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.returnFailMsg(e.getMessage());
        }finally {
            bookControllerMap.remove(judgeKey);
        }
    }

    /**
     * 删除书籍
     * @author linyukun
     * @date 2022-07-11 19:11
     */
    @RequestMapping(value="/delBook",method = RequestMethod.POST)
    public Result delBook(@RequestBody BookDTO dto){
        String judgeKey = "delBook" + bookControllerMapSeparator + dto.getId();
        try{
            loginServiceImpl.judgeIsOnTimeRequest(bookControllerMap, judgeKey);
            String userName = loginServiceImpl.isLogin();
            dto.setDeleteUser(userName);
            return ResultUtil.returnDataSuccess(bookServiceImpl.delBook(dto));
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.returnFailMsg(e.getMessage());
        }finally {
            bookControllerMap.remove(judgeKey);
        }
    }

    /**
     * 根据书籍id获取书籍信息
     * @author linyukun
     * @date 2022-07-09 10:36
     */
    @RequestMapping(value="/getBookById",method = RequestMethod.POST)
    public Result getBookById(@RequestBody BookDTO dto){
        try{
            loginServiceImpl.isLogin();
            return ResultUtil.returnDataSuccess(bookServiceImpl.getBookById(dto));
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.returnFailMsg(e.getMessage());
        }
    }


    @RequestMapping("/saveBookPic")
    public String bannerUpdate(MultipartFile file) throws IOException {
        MultipartFile[] files = new MultipartFile[]{file};
        //保存图片文件到本地并返回相对路径
        //List<String> image = LykFileUtil.uploads("/planCat_file/", files, "image");
        String currentPath = System.getProperty("user.dir");
        List<String> image = LykFileUtil.uploads(imageUploadPath, files, "image");
        //拿着图片路径存储到数据库或者做其他处理,这里就先不多写了，自行发挥
        if(!CollectionUtils.isEmpty(image)){
            //return image.get(0).replace("/view/src/main/resources/static/","");
            return currentPath + image.get(0);
        }else{
            return "";
        }
    }

    @RequestMapping("/getLocalSystemPic")
    public void getLocalSystemPic(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String filePath = request.getParameter("filePath").toString();
        if(StringUtils.isBlank(filePath)){
            filePath = "D:\\gitee-workspace/view/src/main/resources/static/images/book/book-default-small.gif";
        }
        File file = null;
        file = new File(filePath);
        if (file.exists()) {
            try {

                FileInputStream in = new FileInputStream(file);
                byte[] buf = new byte[(int) in.available()];
                in.read(buf);
                //response.setContentType(contentType);
                OutputStream toClient = response.getOutputStream();
                toClient.write(buf);
                toClient.flush();
                toClient.close();
                in.close();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }

    //爬虫
    @RequestMapping("/reptileList")
    public Result reptileList(HttpServletRequest request,HttpServletResponse response) throws IOException {
        return ResultUtil.returnDataSuccess(bookServiceImpl.reptileList());
    }

    //广州图书馆获取isbn信息
    @RequestMapping("/getRemoteIsbn")
    public Result getRemoteIsbn(@RequestBody BookDTO dto,HttpServletRequest request) throws IOException {
        return ResultUtil.returnDataSuccess(bookServiceImpl.getRemoteIsbn(dto));
    }

    /**
     * 获取图书列表（用户） 项目亮点
     * @author linyukun
     * @date 2022-10-22
     */
    @RequestMapping(value="/getBookListUser",method = RequestMethod.POST)
    public Result getBookListUser(@RequestBody BookDTO dto){
        try{
            loginServiceImpl.isLogin();
            return ResultUtil.returnDataSuccess(bookServiceImpl.getBookListUser(dto));
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.returnFailMsg(e.getMessage());
        }
    }



}
